from django.forms.models import ModelForm
from szachy.models import Game, FBUser
from django import forms
from szachy.chess import ParseError, WHITE, KNIGHT, BISHOP, QUEEN, ROOK


class GameForm(ModelForm):
    class Meta:
        model = Game

class MoveForm(forms.Form):
    your_move = forms.CharField(required=True)
    
    
    def __init__(self, data=None, game=None):
        super(MoveForm, self).__init__(data)
        self.game = game      
        
    def clean_your_move(self):
        move = self.cleaned_data['your_move']
        print move
        promotion = None
        if len(move.split('-'))==3:
            promotion=move[-1]
        
        game = self.game.game
        if len(move)>2 and move[0] in 'abcdefgh' and move[1] in '12345678':
            move = '%s%s' %  (str(game.board[move[:2]]).upper(), move)
        
        try:      
            print move      
            move = game.board.parse(move)
            
        except ParseError, error:
            raise forms.ValidationError(str(error))
            
        if not game.move(move):
            raise forms.ValidationError("Illegal move")
    
    def save(self):
        self.game.mark_done_move()
        if self.game.game.board.get_turn() == WHITE:
            self.game.current_move = self.game.white_player
        else:
            self.game.current_move = self.game.black_player
        self.game.save()
            
        
class SideChoiceForm(forms.Form):
    side = forms.CharField(label='Your side', widget=forms.RadioSelect(choices=(('b', 'Black'), ('w', 'White'))))
    
    def __init__(self, data=None, game=None, player=0):
        super(SideChoiceForm, self).__init__(data)
        self.game = game
        if player:
            self.player = FBUser.objects.get_by_id(int(player))
        else:
            self.player = 0
    
    def clean_side(self):
        side = self.cleaned_data['side']
        if self.game.p1 == self.player:
            self.game.p1_state = side
        elif self.game.p2 == self.player:
            self.game.p2_state = side
        else:
            raise forms.ValidationError('You do not play in this match!')
        if self.game.p2_state == self.game.p1_state:
            raise forms.ValidationError('You cannot play the same side as opponent!')
        return side
    
    def save(self):
        self.game.save()
    
    